package com.leoren.run.utils;

import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 时间Util
 */
public class TimeUtils {

    private Timer timer = null;
    private TimerTask timerTask = null;
    private Handler handler = null;
    public  long count = 1;
    private boolean isPause = false;
    private static int delay = 1000;
    private static int period = 1000;
    private static final int UPDATE_TEXTVIEW = 0;
    private TextView textView ;

    public TextView getTextView() {
        return textView;
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }

    public TimeUtils(TextView textView) {
        this.handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case UPDATE_TEXTVIEW:
                        updateTextView();
                        break;
                    default:
                        break;
                }
            }
        };
        this.textView = textView;
    }

    public void pauseTime(){
        isPause = !isPause;
    }

    public void updateTextView(){
        int i = 1000;
        long time= count * i;
        CharSequence sysTimeStr = DateFormat.format("mm:ss", time);
        textView.setText(String.valueOf(sysTimeStr));
    }

    public void startTime(){
        if(timer == null){
            timer = new Timer();
        }
        if(timerTask == null){
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(UPDATE_TEXTVIEW);
                    do {
                        try {
                            Thread.sleep(1000);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }while (isPause);
                    count++;
                }
            };
        }
        if(timer != null && timerTask != null){
            timer.schedule(timerTask, delay, period);
        }
    }

    public void stopTimer(){
        if(timer !=null){
            timer.cancel();
            timer = null;
        }
        if(timerTask != null){
            timerTask.cancel();
            timerTask = null;
        }
        count = 1;
    }

    public void sendMessage(int id){
        if(handler != null){
            Message message = Message.obtain(handler, id);
            handler.sendMessage(message);
        }
    }

}
